package com.py.framework.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.UserCacheHelper;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.entity.SysLogEntity;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.BeanUtil;
import com.py.framework.core.utils.SerializingUtil;
import com.py.framework.entity.AreaEntity;
import com.py.framework.entity.DictDetailEntity;
import com.py.framework.entity.LogEntity;
import com.py.framework.entity.MenuEntity;
import com.py.framework.entity.MenuTree;
import com.py.framework.entity.OfficeEntity;
import com.py.framework.entity.SysMsgEntity;
import com.py.framework.entity.UserEntity;
import com.py.framework.enums.MenuType;
import com.py.framework.service.AuthenticationService;
import com.py.framework.service.MenuResourceService;
import com.py.framework.service.SysMsgService;
import com.py.framework.service.UserService;

/**
 * 对外接口鉴权数据Controller
 *
 * @author Leegern
 * @date 2018年4月26日
 */
@RestController
@RequestMapping("/auth")
public class AuthenticationController extends SystemController {

	@Autowired
	private AuthenticationService authenticationService;
	@Autowired
	private MenuResourceService menuResourceService;

	/**
	 * 用户Service
	 **/
	@Autowired
	private UserService userService;
	@Autowired
	private SysMsgService sysMsgService;

	/**
	 * @api {post} /auth/isValidUser.do 检验用户是否是有效用户
	 * @apiName isValidUser
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/isValidUser", method = RequestMethod.POST)
	public RestServiceResult<Map<String, Object>> isValidUser(HttpServletRequest request) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			// 检验用户权限
			if (UserCacheHelper.isValidUser(SerializingUtil.serialize(jdToken))) {
				result.setCode(RestServiceResult.CODE_SUCCESS);
			} else {
				result.setCode(RestServiceResult.CODE_LOGOUT);
			}
		} else {
			result.setCode(RestServiceResult.CODE_LOGOUT);
		}
		return result;
	}

	/**
	 * @api {post} /auth/hasValidResource.do 检验是否有访问此资源权限
	 * @apiName hasValidResource
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {String} resource 资源地址
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/hasValidResource", method = RequestMethod.POST)
	public @ResponseBody RestServiceResult<Map<String, Object>> hasValidResource(HttpServletRequest request,
			String resource) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		// String jdToken = HttpServletHelper.getUserToken(request);
		// if (StringUtils.isNotBlank(jdToken)) {
		// // 检验用户是否有访问此资源权限
		// try {
		// if (StringUtils.isNotBlank(resource)
		// && UserCacheHelper.isValidUser(SerializingUtil.serialize(jdToken))) {
		// if (authenticationService.hasValidResource(jdToken, resource)) {
		// result.setCode(RestServiceResult.CODE_SUCCESS);
		// } else {
		// result.setCode(RestServiceResult.CODE_NOAUTH);
		// }
		// } else {
		// result.setCode(RestServiceResult.CODE_LOGOUT);
		// }
		// } catch (Exception e) {
		// ExceptionLogger.error(e);
		// result.setCode(RestServiceResult.CODE_UNKNOW);
		// }
		// } else {
		// result.setCode(RestServiceResult.CODE_LOGOUT);
		// }

		 String jdToken = HttpServletHelper.getUserToken(request);
		 if (StringUtils.isNotBlank(jdToken)) {
		 // 检验用户是否登录
		 try {
		 if (StringUtils.isNotBlank(resource)
		 && UserCacheHelper.isValidUser(SerializingUtil.serialize(jdToken))) {
			 result.setCode(RestServiceResult.CODE_SUCCESS);
		 } else {
		 result.setCode(RestServiceResult.CODE_LOGOUT);
		 }
		 } catch (Exception e) {
		 ExceptionLogger.error(e);
		 result.setCode(RestServiceResult.CODE_UNKNOW);
		 }
		 } else {
		 result.setCode(RestServiceResult.CODE_LOGOUT);
		 }
		return result;
	}

	/**
	 * @api {post} /auth/isValidResource.do 检验是否有访问此资源权限
	 * @apiName isValidResource
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {String} resource 访问资源
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/isValidResource", method = RequestMethod.POST)
	public @ResponseBody RestServiceResult<Map<String, Object>> isValidResource(HttpServletRequest request,
			String resource) {
		RestServiceResult<Map<String, Object>> result = new RestServiceResult<Map<String, Object>>();
		result.setCode(RestServiceResult.CODE_NOAUTH);
		result.setMsg(StringUtils.EMPTY);
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				// 检验用户是否有访问此资源权限
				if (StringUtils.isNotBlank(resource)
						&& UserCacheHelper.isValidUser(SerializingUtil.serialize(jdToken))) {
					if (authenticationService.hasValidResource(jdToken, resource)) {
						result.setCode(RestServiceResult.CODE_SUCCESS);
					}
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return result;
	}

	/**
	 * @api {post} /auth/getCurrentUser.do 获取当前用户信息
	 * @apiName getCurrentUser
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} realName 真实姓名
	 * @apiSuccess {String} mobilePhone 手机号
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"username":"admin","realName":"管理员","mobilePhone":"1371370993","officeId":100,"userType":1,"officeName":"南京市"}}
	 */
	@RequestMapping(value = "/getCurrentUser", method = RequestMethod.POST)
	public RestServiceResult<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				// 用户信息
				UserEntity user = authenticationService.getCurrentUserInfo(jdToken);
				if (null != user && user.getId() > Constants.NUMBER_ZERO) {
					// 用户部门信息
					OfficeEntity office = authenticationService.getCurrentUserOffice(jdToken);
					result.putAll(BeanUtil.populateBean2Map(user));
					if (null != office) {
						Map<String, Object> officeMap = BeanUtil.populateBean2Map(office);
						if (!CollectionUtils.isEmpty(officeMap)) {
							officeMap.remove("id");
							result.putAll(officeMap);
						}
					}
					result.remove("password");
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getCurrentUserMenuResources.do 获取当前用户菜单资源数据
	 * @apiName getCurrentUserMenuResources
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":3,"data":
	 *                    [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getCurrentUserMenuResources", method = RequestMethod.POST)
	public RestServiceResult<List<MenuEntity>> getCurrentUserMenuResources(HttpServletRequest request) {
		List<MenuEntity> result = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				result = authenticationService.getCurrentUserMenuResources(jdToken);
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getCurrentUserMenus.do 获取当前用户菜单数据
	 * @apiName getCurrentUserMenus
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 菜单Id
	 * @apiSuccess {long} parentId 父菜单Id
	 * @apiSuccess {String} name 菜单地址
	 * @apiSuccess {String} title 菜单名称
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    [{"id":10,"title":"资源管理","parentId":1,"menuType":1,"name":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getCurrentUserMenus", method = RequestMethod.POST)
	public RestServiceResult<List<MenuTree>> getCurrentUserMenus(HttpServletRequest request) {
		List<MenuEntity> result = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				List<MenuEntity> datas = authenticationService.getCurrentUserMenuResources(jdToken);
				if (!CollectionUtils.isEmpty(datas)) {
					for (MenuEntity menu : datas) {
						if (null != menu && (menu.getMenuType() == MenuType.TYPE_1.getValue()
								|| menu.getMenuType() == MenuType.TYPE_2.getValue()
								|| menu.getMenuType() == MenuType.TYPE_3.getValue()
								|| menu.getMenuType() == MenuType.TYPE_5.getValue())) {
							result.add(menu);
						}
					}
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		// 组装用户菜单树
		List<MenuTree> datas = this.populateMenuTrees(result);
		return super.getSuccessRestServiceResult(datas);
	}

	/**
	 * @api {post} /auth/getCurrentUserThirdMenus.do 获取当前用户功能菜单
	 * @apiName getCurrentUserThirdMenus
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} menuName 菜单名称
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} menuType 菜单类型，1：子系统，2：模块，3：功能，4：资源
	 * @apiSuccess {String} linkUrl 后台路由
	 * @apiSuccess {String} routeAddr 前台路由地址
	 * @apiSuccess {String} icon ICON图标
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} isShow 是否显示，1：是，2：否
	 * @apiSuccess {int} isWinOpen 是否新窗口打开，1：是，2：否
	 * @apiSuccess {String} parentMenuName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":1,"data":
	 *                    [{"menuName":"资源管理","parentId":1,"menuType":1,"linkUrl":"http://xxx.com","routeAddr":"menu_sys","orderBy":1,"isShow":1,"isWinOpen":1,"icon":"header.ico"}]}
	 */
	@RequestMapping(value = "/getCurrentUserThirdMenus", method = RequestMethod.POST)
	public RestServiceResult<List<MenuEntity>> getCurrentUserThirdMenus(HttpServletRequest request) {
		List<MenuEntity> result = new ArrayList<>();
		List<MenuEntity> tmpList = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				List<MenuEntity> datas = authenticationService.getCurrentUserMenuResources(jdToken);
				if (!CollectionUtils.isEmpty(datas)) {
					for (MenuEntity menu : datas) {
						if (null != menu && menu.getMenuType() == MenuType.TYPE_1.getValue()) {
							tmpList.add(menu);
						}
					}
					for (MenuEntity entity : tmpList) {
						for (MenuEntity menu : datas) {
							if (null != menu && menu.getMenuType() == MenuType.TYPE_3.getValue()
									&& (menu.getAllParentId().indexOf(String.valueOf(entity.getId())) != -1)) {
								menu.setParentMenuName(entity.getMenuName());
								menu.setParentId(entity.getId());
								result.add(menu);
							}
						}
					}
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		// 组装用户菜单树
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getCurrentUserOffices.do 获取当前用户部门以及子部门数据
	 * @apiName getCurrentUserOffices
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":3,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getCurrentUserOffices", method = RequestMethod.POST)
	public RestServiceResult<List<OfficeEntity>> getCurrentUserOffices(HttpServletRequest request) {
		List<OfficeEntity> result = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				result = authenticationService.getCurrentUserOffices(jdToken);
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getCurrentUserAreas.do 获取当前用户区域以及子区域数据
	 * @apiName getCurrentUserAreas
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":3,"data":[{"areaName":"南京市","areaCode":"10009","parentId":1,"orderBy":1,"parentAreaName":"江苏省"}]}
	 */
	@RequestMapping(value = "/getCurrentUserAreas", method = RequestMethod.POST)
	public RestServiceResult<List<AreaEntity>> getCurrentUserAreas(HttpServletRequest request) {
		List<AreaEntity> result = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				result = authenticationService.getCurrentUserAreas(jdToken);
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getAllAreas.do 获取所有区域数据
	 * @apiName getAllAreas
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {long} areaId 区域Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果 {"code":0,"msg":"","count":0,"data":
	 *                    [{"id":1,"createTime":1525244806000,"updateTime":1525244799000,"delFlag":1,
	 *                    "areaName":"江苏省","areaCode":"32000","parentId":0,"allParentId":"","orderBy":1}]}
	 */
	@RequestMapping(value = "/getAllAreas", method = RequestMethod.POST)
	public RestServiceResult<List<AreaEntity>> getAllAreas(HttpServletRequest request,
			@RequestParam(value = "areaId", required = false, defaultValue = "0") long areaId) {
		List<AreaEntity> areas = authenticationService.getAllAreasById(areaId);
		return super.getSuccessRestServiceResult(areas);
	}

	/**
	 * @api {post} /auth/getRootArea.do 获取顶级区域信息
	 * @apiName getRootArea
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":{"areaName":"南京市","areaCode":"10009","parentId":1,"orderBy":1,"parentAreaName":"江苏省"}}
	 */
	@RequestMapping(value = "/getRootArea", method = RequestMethod.POST)
	public RestServiceResult<AreaEntity> getRootArea(HttpServletRequest request) {
		AreaEntity area = authenticationService.getRootArea();
		return super.getSuccessRestServiceResult(area);
	}

	/**
	 * @api {post} /auth/getSecondAreas.do 获取二级区域数据
	 * @apiName getSecondAreas
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"areaName":"南京市","areaCode":"10009","parentId":1,"orderBy":1,"parentAreaName":"江苏省"}]}
	 */
	@RequestMapping(value = "/getSecondAreas", method = RequestMethod.POST)
	public RestServiceResult<List<AreaEntity>> getSecondAreas(HttpServletRequest request) {
		List<AreaEntity> areas = authenticationService.getSecondAreas();
		return super.getSuccessRestServiceResult(areas);
	}

	/**
	 * @api {post} /auth/getAreasByParentId.do 根据父区域Id查询子区域信息
	 * @apiName getAreasByParentId
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {long} parentId 父区域Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"areaName":"南京市","areaCode":"10009","parentId":1,"orderBy":1,"parentAreaName":"江苏省"}]}
	 */
	@RequestMapping(value = "/getAreasByParentId", method = RequestMethod.POST)
	public RestServiceResult<List<AreaEntity>> getAreasByParentId(HttpServletRequest request,
			@RequestParam(value = "parentId", required = false, defaultValue = "0") long parentId) {
		List<AreaEntity> result = new ArrayList<>();
		if (parentId > Constants.NUMBER_ZERO) {
			List<AreaEntity> areas = authenticationService.getAreasByParentId(parentId);
			result.addAll(areas);
		} else {
			AreaEntity area = authenticationService.getRootArea();
			result.add(area);
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * @api {post} /auth/getAreasByIds.do 根据区域Id集合查询区域信息
	 * @apiName getAreasByIds
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request
	 * @apiParam {String} ids
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"areaName":"南京市","areaCode":"10009","parentId":1,"orderBy":1,"parentAreaName":"江苏省"}]}
	 */
	@RequestMapping(value = "/getAreasByIds", method = RequestMethod.POST)
	public RestServiceResult<List<AreaEntity>> getAreasByIds(HttpServletRequest request, String ids) {
		List<AreaEntity> areas = null;
		if (StringUtils.isNotBlank(ids)) {
			areas = authenticationService.getAreasByIds(super.convert2Long(ids));
		}
		return super.getSuccessRestServiceResult(areas);
	}

	/**
	 * @api {post} /auth/getSubUsersById.do 根据用户Id获取用户下级所有部门用户信息
	 * @apiName getSubUsersById
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {long} userId 用户Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} realName 真实姓名
	 * @apiSuccess {String} mobilePhone 手机号
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"username":"admin","realName":"管理员","mobilePhone":"1371370993","officeId":100,"userType":1,"officeName":"南京市"}}
	 */
	@RequestMapping(value = "/getSubUsersById", method = RequestMethod.POST)
	public RestServiceResult<List<UserEntity>> getSubUsersById(long userId) {
		List<UserEntity> datas = null;
		if (userId > Constants.NUMBER_ZERO) {
			datas = authenticationService.getSubUsersById(userId);
		}
		return super.getSuccessRestServiceResult(datas);
	}

	/**
	 * @api {post} /auth/getUsersByIds.do 根据用户Id集合查询用户信息
	 * @apiName getUsersByIds
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {String} ids 用户Id集合
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} realName 真实姓名
	 * @apiSuccess {String} mobilePhone 手机号
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"username":"admin","realName":"管理员","mobilePhone":"1371370993","officeId":100,"userType":1,"officeName":"南京市"}}
	 */
	@RequestMapping(value = "/getUsersByIds", method = RequestMethod.POST)
	public RestServiceResult<List<UserEntity>> getUsersByIds(HttpServletRequest request, String ids) {
		List<UserEntity> datas = null;
		if (StringUtils.isNotBlank(ids)) {
			datas = authenticationService.getUsersByIds(super.convert2Long(ids));
		}
		return super.getSuccessRestServiceResult(datas);
	}
	
	@RequestMapping(value = "/getUsers", method = RequestMethod.POST)
	public RestServiceResult<List<UserEntity>> getUsers(HttpServletRequest request) {
		List<UserEntity> datas = authenticationService.getUsers();
		
		return super.getSuccessRestServiceResult(datas);
	}

	/**
	 * @api {post} /auth/getRootOffices.do 获取顶级部门数据
	 * @apiName getRootOffices
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":3,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getRootOffices", method = RequestMethod.POST)
	public RestServiceResult<List<OfficeEntity>> getRootOffices(HttpServletRequest request) {
		List<OfficeEntity> offices = authenticationService.getRootOffices();
		return super.getSuccessRestServiceResult(offices);
	}

	@RequestMapping(value = "/getAreaIdByDeptId")
	public RestServiceResult<Integer> getAreaIdByDeptId(HttpServletRequest request,String deptId) {
		Integer id = authenticationService.getAreaIdByDeptId(deptId);
		return super.getSuccessRestServiceResult(id);
	}

	/**
	 * @api {post} /auth/getOfficeById.do 根据部门Id获取部门信息
	 * @apiName getOfficeById
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {long} officeId 部门Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}}
	 */
	@RequestMapping(value = "/getOfficeById", method = RequestMethod.POST)
	public RestServiceResult<OfficeEntity> getOfficeById(HttpServletRequest request, long officeId) {
		OfficeEntity entity = null;
		if (officeId > Constants.NUMBER_ZERO) {
			entity = authenticationService.getOfficeById(officeId);
		}
		return super.getSuccessRestServiceResult(entity);
	}

	/**
	 * @api {post} /auth/getOfficesByAreaId.do 根据区域Id获取部门信息
	 * @apiName getOfficesByAreaId
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {long} areaId 区域Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getOfficesByAreaId", method = RequestMethod.POST)
	public RestServiceResult<List<OfficeEntity>> getOfficesByAreaId(long areaId) {
		List<OfficeEntity> entity = null;
		if (areaId > Constants.NUMBER_ZERO) {
			entity = authenticationService.getOfficesByAreaId(areaId);
		}
		return super.getSuccessRestServiceResult(entity);
	}

	/**
	 * @api {post} /auth/getAllOffices.do 获取所有部门数据
	 * @apiName getAllOffices
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getAllOffices", method = RequestMethod.POST)
	public RestServiceResult<List<OfficeEntity>> getAllOffices() {
		List<OfficeEntity> entities = authenticationService.getAllOffices();
		return super.getSuccessRestServiceResult(entities);
	}

	/**
	 * @api {post} /auth/getDictDetails.do 根据字典KEY值获取字典详情数据
	 * @apiName getDictDetails
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {String} dictKey 字典KEY值
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dtlKey KEY值
	 * @apiSuccess {String} dtlValue 字典值
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} enabled 是否使用，1否，2是
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"dtlKey":"ITEM_1","dtlValue":"国产电视","orderBy":1,"enabled":2}]}
	 */
	@RequestMapping(value = "/getDictDetails", method = RequestMethod.POST)
	public RestServiceResult<List<DictDetailEntity>> getDictDetails(String dictKey) {
		List<DictDetailEntity> datas = null;
		if (StringUtils.isNotBlank(dictKey)) {
			datas = authenticationService.getDictDetails(dictKey);
		}
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {post} /auth/getDictInfo.do 根据字典KEY值获取字典详情数据
	 * @apiName getDictDetails
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {String} dictKey 字典KEY值
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dtlKey KEY值
	 * @apiSuccess {String} dtlValue 字典值
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} enabled 是否使用，1否，2是
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"dtlKey":"ITEM_1","dtlValue":"国产电视","orderBy":1,"enabled":2}]}
	 */
	@RequestMapping(value = "/getDictInfo", method = RequestMethod.POST)
	public RestServiceResult<List<LinkedHashMap>> getDictInfo() {
		List<LinkedHashMap> datas = null;
	
			datas = authenticationService.seletctDictInfo();
		
		return super.getSuccessRestServiceResult(datas);
	}

	/**
	 * @api {post} /auth/getDictDetail.do 根据字典KEY值和明细KEY获取字典详情数据
	 * @apiName getDictDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {String} dictKey 字典KEY值
	 * @apiParam {String} dtlKey 明细KEY值
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集 数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} dtlKey KEY值
	 * @apiSuccess {String} dtlValue 字典值
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} enabled 是否使用，1否，2是
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"dtlKey":"ITEM_1","dtlValue":"国产电视","orderBy":1,"enabled":2}]}
	 */
	@RequestMapping(value = "/getDictDetail", method = RequestMethod.POST)
	public RestServiceResult<DictDetailEntity> getDictDetail(String dictKey, String dtlKey) {
		DictDetailEntity data = null;
		if (StringUtils.isNotBlank(dictKey)) {
			data = authenticationService.getDictDetail(dictKey, dtlKey);
		}
		return super.getSuccessRestServiceResult(data);
	}

	/**
	 * @api {post} /auth/sendSysMsg.do 发送系统站内信
	 * @apiName sendSysMsg
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {SysMsgEntity} msgs 消息集合
	 * @apiParam {String} msgTitle 标题
	 * @apiParam {String} msgContent 内容
	 * @apiParam {String} sendId 发件人ID
	 * @apiParam {String} linkUrl 链接地址
	 * @apiParam {int} msgStatus 消息状态，1：未读，2：已读
	 * @apiParamExample {json} 请求参数示例
	 *                  [{"msgTitle":"通知","msgContent":"周五放假","sendId":10,"linkUrl":"/send/msg.do","msgStatus":1}]
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/sendSysMsg", method = RequestMethod.POST)
	public RestServiceResult<Object> sendSysMsg(HttpServletRequest request, @RequestBody List<SysMsgEntity> msgs) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (!CollectionUtils.isEmpty(msgs)) {
			try {
				authenticationService.sendSysMsg(jdToken, msgs);
				result.setCode(RestServiceResult.CODE_SUCCESS);
			} catch (Exception e) {
				ExceptionLogger.error(e);
				result.setCode(RestServiceResult.CODE_UNKNOW);
			}
		}
		return result;
	}

	/**
	 * @api {post} /auth/postOperateLog.do 添加用户操作日志
	 * @apiName postOperateLog
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {SysLogEntity} entity 日志实例
	 * @apiParam {String} username 用户名
	 * @apiParam {String} realName 真实姓名
	 * @apiParam {String} requestIp 请求IP
	 * @apiParam {String} requestUrl 请求资源URL
	 * @apiParam {String} shortRequestUrl 请求资源URL(去除根路径)
	 * @apiParam {String} requestContent 请求内容
	 * @apiParam {int} logType 日志类型：1：系统日志，2：登录日志
	 * @apiParamExample {json} 请求参数示例
	 *                  {"username":"zhangsan","realName":"张三","requestIp":"10.0.0.1","requestUrl":"/syslog/addLogInfo.json","shortRequestUrl":"/syslog/addLogInfo.json","logType":1,"requestContent":"params=222"}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/postOperateLog", method = RequestMethod.POST)
	public RestServiceResult<Object> postOperateLog(HttpServletRequest request, @RequestBody SysLogEntity entity) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			if (null != entity) {
				LogEntity logEntity = new LogEntity();
				String jdToken = HttpServletHelper.getUserToken(request);
				if (StringUtils.isNotBlank(jdToken)) {
					byte[] bts = UserCacheHelper.getUserFromCache(SerializingUtil.serialize(jdToken));
					if (null != bts && bts.length > Constants.NUMBER_ZERO) {
						UserEntity user = (UserEntity) SerializingUtil.deserialize(bts);
						if (null != user) {
							if (null != user.getUsername() && user.getUsername().length() > Constants.NUMBER_ZERO) {
								logEntity.setUsername(user.getUsername());
								logEntity.setRealName(user.getRealName());
							}
						}
					}
				}
				// 获取请求地址
				String requestPath = request.getRequestURI();
				String servletPath = request.getServletPath();

				if (StringUtils.isBlank(servletPath)) {
					String ctxPath = request.getContextPath();
					servletPath = requestPath.replaceFirst(ctxPath, "");
				}

				MenuEntity m = menuResourceService.getMenuNameByLinkURL(servletPath);
				if (m != null) {
					logEntity.setRequestDesc(m.getMenuName());
					logEntity.setSysName(entity.getSysName());
					logEntity.setLogType(Constants.NUMBER_ONE);
					logEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
					logEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
					logEntity.setDelFlag(Constants.NUMBER_ONE);
					if (StringUtils.isNotBlank(entity.getRequestContent())
							&& entity.getRequestContent().length() > 950) {
						logEntity.setRequestContent(entity.getRequestContent().substring(0, 950));
					} else {
						logEntity.setRequestContent(entity.getRequestContent());
					}
					logEntity.setRequestIp(entity.getRequestIp());
					logEntity.setRequestUrl(entity.getRequestUrl());
					logEntity.setShortRequestUrl(entity.getShortRequestUrl());
					// 系统日志放入缓冲队列
					authenticationService.sendLogToQueue(logEntity);
				}
				result.setCode(RestServiceResult.CODE_SUCCESS);
			} else {
				result.setCode(RestServiceResult.CODE_SUCCESS);
			}
		} catch (Exception e) {
			ExceptionLogger.error(e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
		}
		return result;
	}

	/**
	 * @api {get} /auth/getDeptAdmins.do 获取部门管理员信息
	 * @apiName getDeptAdmins
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {String} deptIds 部门ID
	 * @apiParamExample {json} 请求参数示例 {"deptId":"1,2,3,4"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"username":"admin","realName":"管理员","mobilePhone":"1371370993","officeId":100,"userType":1,"officeName":"南京市"}}
	 */
	@RequestMapping(value = "/getDeptAdmins", method = RequestMethod.POST)
	public RestServiceResult<List<UserEntity>> getAllDeptAdmin(@RequestParam(value = "deptIds") String deptIds) {
		try {
			List<UserEntity> deptAdmins = authenticationService.getAllDeptAdmin(super.convert2Long(deptIds));
			return super.getSuccessRestServiceResult(deptAdmins);
		} catch (Exception e) {
			return super.getFailedRestServiceResult("获取部门管理员信息异常！");
		}

	}

	/**
	 * 组装用户菜单树
	 *
	 * @param menus
	 * @return
	 */
	private List<MenuTree> populateMenuTrees(List<MenuEntity> menus) {
		List<MenuTree> trees = new ArrayList<>();
		MenuTree treeNode = null;
		if (!CollectionUtils.isEmpty(menus)) {
			for (MenuEntity menu : menus) {
				// 先找到所有的一级菜单
				if (null != menu && Constants.NUMBER_ZERO == menu.getParentId()) {
					treeNode = this.toMenuTree(menu);
					trees.add(treeNode);
				}
			}
			// 为一级菜单设置子菜单，getChild是递归调用的
			for (MenuTree menu : trees) {
				menu.setList(getChild(menu.getId(), menus));
			}
		}
		return trees;
	}

	/**
	 * 递归查找子菜单
	 *
	 * @param id
	 *            当前菜单id
	 * @param rootMenu
	 *            要查找的列表
	 * @return
	 */
	private List<MenuTree> getChild(long id, List<MenuEntity> menus) {
		// 子菜单
		List<MenuTree> childList = new ArrayList<>();
		MenuTree treeNode = null;
		for (MenuEntity menu : menus) {
			// 遍历所有节点，将父菜单id与传过来的id比较
			if (menu.getParentId() > Constants.NUMBER_ZERO) {
				if (menu.getParentId() == id) {
					treeNode = this.toMenuTree(menu);
					childList.add(treeNode);
				}
			}
		}
		// 把子菜单的子菜单再循环一遍
		for (MenuTree menu : childList) {
			// 菜单类型不是资源的子菜单还有子菜单
			if (menu.getMenuType() != MenuType.TYPE_4.getValue()) {
				// 递归
				menu.setList(getChild(menu.getId(), menus));
			}
		}
		// 递归退出条件
		if (childList.size() == Constants.NUMBER_ZERO) {
			return null;
		}
		return childList;
	}

	/**
	 * 转换菜单实体
	 *
	 * @param menu
	 * @return
	 */
	private MenuTree toMenuTree(MenuEntity menu) {
		MenuTree tree = new MenuTree();
		if (null != menu) {
			tree.setId(menu.getId());
			tree.setParentId(menu.getParentId());
			tree.setName(menu.getRouteAddr());
			tree.setTitle(menu.getMenuName());
			tree.setIcon(menu.getIcon());
			tree.setOrderBy(menu.getOrderBy());
			tree.setMenuType(menu.getMenuType());
			tree.setIsShow(menu.getIsShow());
			tree.setIsWinOpen(menu.getIsWinOpen());
		}
		return tree;
	}

	/**
	 * @api {post} /auth/getOfficeById.do 根据部门Id获取部门信息
	 * @apiName getOfficeById
	 * @apiVersion 0.0.1
	 * @apiGroup 对外接口
	 * @apiParam {HttpServletRequest} request 请求实例
	 * @apiParam {long} officeId 部门Id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}}
	 */
	@RequestMapping(value = "/getLoginTimesByDept", method = RequestMethod.POST)
	public RestServiceResult<List<Map>> getLoginTimesByDept(HttpServletRequest request) {
		List<Map> list = null;
		list = authenticationService.getLoginTimesByDept();
		return super.getSuccessRestServiceResult(list);
	}

	@RequestMapping(value = "/getDeptAllUsers", method = RequestMethod.POST)
	public RestServiceResult<List<UserEntity>> getDeptAllUsers(@RequestParam(value = "deptId") String deptId) {
		try {

			List<UserEntity> users = authenticationService.getDeptAllUsers(deptId);

			return super.getSuccessRestServiceResult(users);
		} catch (Exception e) {
			return super.getFailedRestServiceResult("获取部门用户信息异常！");
		}

	}

	@RequestMapping(value = "/getDeptManager", method = RequestMethod.POST)
	public RestServiceResult<List<Long>> getDeptManager(@RequestParam(value = "deptIds") String deptIds,
			HttpServletRequest request) {
		List<Long> result = new ArrayList<>();
		String jdToken = HttpServletHelper.getUserToken(request);
		if (StringUtils.isNotBlank(jdToken)) {
			try {
				result = authenticationService.getDeptManager(super.convert2Long(deptIds));
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	@RequestMapping(value = "/getDataCollectionMessageNum", method = RequestMethod.POST)
	public RestServiceResult<Integer> getDataCollectionMessageNum() {

		int result = sysMsgService.getDataCollectionMessageNum();

		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * 根据用户名获取用户信息(巩义接口、联合奖惩接口专用)
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/getByUsername", method = RequestMethod.POST)
	public RestServiceResult<UserEntity> getByUsername(@RequestParam(value = "username") String username) {
		RestServiceResult<UserEntity> result = new RestServiceResult<UserEntity>();
		result.setData(userService.getUserByTwoPrincipal(username));
		return result;
	}

	/**
	 * 根据用户名获取用户信息(联合奖惩接口专用)
	 * @param deptId
	 * @return
	 */
	@RequestMapping(value = "/getLhjcToken", method = RequestMethod.POST)
	public RestServiceResult<String> getLhjcToken(@RequestParam(value = "deptId") String deptId) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		result.setData(userService.getLhjcToken(Long.parseLong(deptId)));
		return result;
	}

	/**
	 * 获取部门管理员的所有顶级部门id
	 * @return
	 */
	@RequestMapping(value = "/getManagerDeptList", method = RequestMethod.POST)
	public RestServiceResult<List<LinkedHashMap>> getManagerDeptList() {
		RestServiceResult<List<LinkedHashMap>> result = new RestServiceResult<List<LinkedHashMap>>();
		result.setData(userService.getManagerDeptList());
		return result;
	}
}